{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Regressão Linear Simples - Trabalho\n",
    "\n",
    "## Estudo de caso: Seguro de automóvel sueco\n",
    "\n",
    "Agora, sabemos como implementar um modelo de regressão linear simples. Vamos aplicá-lo ao conjunto de dados do seguro de automóveis sueco. Esta seção assume que você baixou o conjunto de dados para o arquivo insurance.csv, o qual está disponível no notebook respectivo.\n",
    "\n",
    "O conjunto de dados envolve a previsão do pagamento total de todas as reclamações em milhares de Kronor sueco, dado o número total de reclamações. É um dataset composto por 63 observações com 1 variável de entrada e 1 variável de saída. Os nomes das variáveis são os seguintes:\n",
    "\n",
    "1. Número de reivindicações.\n",
    "2. Pagamento total para todas as reclamações em milhares de Kronor sueco.\n",
    "\n",
    "Voce deve adicionar algumas funções acessórias à regressão linear simples. Especificamente, uma função para carregar o arquivo CSV chamado *load_csv ()*, uma função para converter um conjunto de dados carregado para números chamado *str_column_to_float ()*, uma função para avaliar um algoritmo usando um conjunto de treino e teste chamado *split_train_split ()*, a função para calcular RMSE chamado *rmse_metric ()* e uma função para avaliar um algoritmo chamado *evaluate_algorithm()*.\n",
    "\n",
    "Utilize um conjunto de dados de treinamento de 60% dos dados para preparar o modelo. As previsões devem ser feitas nos restantes 40%. \n",
    "\n",
    "Compare a performabce do seu algoritmo com o algoritmo baseline, o qual utiliza a média dos pagamentos realizados para realizar a predição ( a média é 72,251 mil Kronor).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "import csv\n",
    "import random\n",
    "from math import sqrt\n",
    "\n",
    "\n",
    "def loadCsv(filename):\n",
    "    lines = csv.reader(open(filename, \"r\"))\n",
    "    dataset = list(lines)\n",
    "    for i in range(len(dataset)):\n",
    "        dataset[i] = [float(x) for x in dataset[i]]\n",
    "    return dataset\n",
    "\n",
    "\n",
    "def splitDataset(dataset, splitRatio):\n",
    "    trainSize = int(len(dataset) * splitRatio)\n",
    "    trainSet = []\n",
    "    copy = list(dataset)\n",
    "    while len(trainSet) < trainSize:\n",
    "        index = random.randrange(len(copy))\n",
    "        trainSet.append(copy.pop(index))\n",
    "    return [trainSet, copy]\n",
    "\n",
    "def mean(values):\n",
    "    return sum(values) / float(len(values))\n",
    "\n",
    "def variance(values, mean):\n",
    "    return sum([(x-mean)**2 for x in values])\n",
    "\n",
    "def covariance(x, mean_x, y, mean_y):\n",
    "    covar = 0.0\n",
    "    for i in range(len(x)):\n",
    "        covar += (x[i] - mean_x) * (y[i] - mean_y)\n",
    "    return covar\n",
    "\n",
    "def coefficients(dataset):\n",
    "    x = [row[0] for row in dataset]\n",
    "    y = [row[1] for row in dataset]\n",
    "    x_mean, y_mean = mean(x), mean(y)\n",
    "    b1 = (covariance(x, x_mean, y, y_mean) / variance(x, x_mean))\n",
    "    b0 = y_mean - b1 * x_mean\n",
    "    return [b0, b1]\n",
    "\n",
    "def simple_linear_regression(train, test):\n",
    "    predictions = list()\n",
    "    c0, c1 = coefficients(train)\n",
    "    for row in test:\n",
    "        ypred = c0 + c1 * row[0]\n",
    "        predictions.append(ypred)\n",
    "    return predictions\n",
    "\n",
    "\n",
    "def rmse_metric(actual, predicted):\n",
    "    sum_error = 0.0\n",
    "    for i in range(len(actual)):\n",
    "        prediction_error = predicted[i] - actual[i]\n",
    "        sum_error += (prediction_error ** 2)\n",
    "        mean_error = sum_error / float(len(actual))\n",
    "    return sqrt(mean_error)\n",
    "              \n",
    "       \n",
    "                \n",
    "def evaluate_algorithm(dataset, algorithm):\n",
    "    test_set = list()\n",
    "    for row in dataset:\n",
    "        row_copy = list(row)\n",
    "        row_copy[-1] = None\n",
    "        test_set.append(row_copy)\n",
    "                \n",
    "    predicted = algorithm(dataset, test_set)\n",
    "    print(predicted)\n",
    "    actual = [row[-1] for row in dataset]\n",
    "    rmse = rmse_metric(actual, predicted)\n",
    "    return rmse\n",
    "\n",
    "                \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "#média do treino\n",
    "def baseline(y_train, test):\n",
    "    meanValue = np.mean(y_train)\n",
    "    predictions = [meanValue for i in range(len(test))]\n",
    "    return predictions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[388.68743024628236, 84.85713340037577, 64.37419203997757, 443.30860720734427, 156.54742816176946, 214.5824286828977, 98.51242764064123, 67.78801560004393, 173.6165459621013, 54.13272135977847, 37.06360355944664, 183.8580166423004, 57.54654491984484, 98.51242764064123, 43.89125067957937, 26.82213287924754, 101.92625120070761, 40.47742711951301, 30.23595643931391, 98.51242764064123, 40.47742711951301, 50.71889779971211, 50.71889779971211, 30.23595643931391, 118.99536900103944, 43.89125067957937, 33.64977999938027, 88.27095696044213, 43.89125067957937, 33.64977999938027, 19.99448575911481, 105.34007476077397, 40.47742711951301, 37.06360355944664, 95.09860408057487, 57.54654491984484, 228.23772292316318, 60.96036847991121, 33.64977999938027, 74.61566272017667, 64.37419203997757, 224.82389936309679, 159.96125172183582, 146.30595748157037, 207.75478156276498, 159.96125172183582, 57.54654491984484, 112.1677218809067, 47.30507423964574, 30.23595643931391, 78.02948628024305, 64.37419203997757, 64.37419203997757, 71.2018391601103, 47.30507423964574, 118.99536900103944, 122.4091925611058, 101.92625120070761, 50.71889779971211, 125.82301612117217, 67.78801560004393, 200.92713444263222, 108.75389832084034]\n",
      "\n",
      "RMSE: 35.365829968791466\n"
     ]
    }
   ],
   "source": [
    "dataset = loadCsv('insurance.csv')\n",
    "train, test = splitDataset(dataset, 0.6)\n",
    "predictions = simple_linear_regression(train, test)\n",
    "rmse = evaluate_algorithm(dataset, simple_linear_regression)\n",
    "print('\\nRMSE:', rmse)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743,\n",
       " 62.929729729729743]"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "baseline(train,test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
